module Utils {

	/**
	 * ajax egret.HttpRequest
	 * @{
	 * 	method?:'GET/POST',
	 *  url:'请求地址',
	 * 	data?:{} 参数使用对象格式,
	 * 	headers?:'application/x-www-form-urlencoded||application/json'
	 * }
	 * 用法示例:
	 * Utils.ajax({url:'',data:{}}).then(res=>{}).catch(err=>{})
	 */

	export function ajax(ajaxObj: ajaxObj) {
		/**
		 * Url 默认连接前缀
		 */
		const Url = ''
		/**
		 * 设置headers 
		 */
		ajaxObj.headers = 'application/json'
		return new Promise((resolve: (value: any) => void, reject) => {
			var params = ''
			if (ajaxObj.data) {
				if (ajaxObj.headers) {
					if (ajaxObj.headers == 'application/json') {
						params = JSON.stringify(ajaxObj.data)
					}
				} else {
					for (var key in ajaxObj.data) {
						if (ajaxObj.data.hasOwnProperty(key)) {
							var element = ajaxObj.data[key];
							if (params == '') {
								params += `${key}=${element}`
							} else {
								params += `&${key}=${element}`
							}
						}
					}
				}
			}
			var request = new egret.HttpRequest();
			request.responseType = egret.HttpResponseType.TEXT;
			request.open(ajaxObj.url.substring(0, 4) == 'http' ? ajaxObj.url : Url + ajaxObj.url, ajaxObj.method ? egret.HttpMethod[ajaxObj.method.toLocaleUpperCase()] : egret.HttpMethod.POST);
			request.setRequestHeader("Content-Type", ajaxObj.headers ? ajaxObj.headers : "application/x-www-form-urlencoded");
			request.send(params);
			request.addEventListener(egret.Event.COMPLETE, (event) => {
				var request = <egret.HttpRequest>event.currentTarget;
				var data = JSON.parse(request.response)
				if (data.success) {
					resolve(data.data)
				} else {
					reject(event)
				}
			}, this);
			request.addEventListener(egret.IOErrorEvent.IO_ERROR, (event: egret.IOErrorEvent) => {
				reject(event)
			}, this);
		});
	}
	interface ajaxObj {
		method?: string,
		url: string,
		data?: Object,
		headers?: string
	}
	/**
	 * 获取OSS 秘钥
	 */
	export const getOSS = async () => {
		return Utils.ajax({
			url: 'http://api.malukeji.com/lbdq/aliyunWebUploadSts/getStsSign.action'
		})
	}
	/**
	 * 地址栏取参
	 * variable:参数名
	 * 用法 Utils.getQueryVariable('参数名字')
	 */
	export const getQueryVariable = (variable) => {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) { return pair[1]; }
		}
		return (false);
	}
	/**
	 * 随机1-12长度的 随机字符串
	 */
	export const randomStr = () => {
		var d,
			e,
			b = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
			c = "",
			a = Math.floor(Math.random() * 12 + 1);
		for (d = 0; a > d; d += 1)
			e = Math.random() * b.length, e = Math.floor(e), c += b.charAt(e);
		return c
	}
	/**
	 * 
	 * @param text 要复制的文本
	 *  返回 true 复制成功
	 */
	export const Copytext = (text: string) => {
		try {
			let input = document.createElement("input");
			input.readOnly = true;
			input.value = text;
			document.body.appendChild(input);
			input.select();
			input.setSelectionRange(0, input.value.length);
			document.execCommand("Copy");
			document.body.removeChild(input);
			return text;
		} catch (e) {
			return false;
		}
	}
	/**
	 * 长按识别二维码
	 * 创建img标签的二维码，在微信里长按扫描识别
	 * @author chenkai
	 * @since 2017/4/17
	 * 
	 * example:
	 * var qrCode:QRCode = new QRCode("resource/assets/qrcode.jpg");
	 * qrCode.setPosition(100, 100, 200, 200,this);
	 * qrCode.showHtmlCode();
	 */
	export class QRCode {
		/**html中<img>标签二维码*/
		private htmlCode: HTMLImageElement;
		/**
		 * @param htmlCodeUrl htmlCode二维码链接
		 */
		public constructor(htmlCodeUrl: string) {
			var gameDiv = document.getElementsByClassName('egret-player')[0];
			this.htmlCode = document.createElement("img");
			this.htmlCode.src = htmlCodeUrl;
			this.htmlCode.style.position = "absolute";
			this.htmlCode.style.opacity = '1.002'
			this.htmlCode.style.display = "none";
			this.htmlCode.draggable = false
			gameDiv.appendChild(this.htmlCode);
		}

		/**
		 * 显示二维码
		 */
		public showHtmlCode(): void {
			if (this.htmlCode) {
				this.htmlCode.style.display = "inline";
			}
		}

		/**隐藏二维码*/
		public hideHtmlCode(): void {
			if (this.htmlCode) {
				this.htmlCode.style.display = "none";
			}
		}

		/**
		 * 设置二维码图片位置
		 * @param xPos x坐标
		 * @param yPos y坐标
		 * @param width 宽度
		 * @param height 高度
		 */
		public setPosition(xPos: number, yPos: number, width: number, height: number, then) {
			if (this.htmlCode == null) {
				return;
			}

			//竖屏
			if (document.body.clientWidth < document.body.clientHeight) {
				var wScale = document.body.clientWidth / then.stage.stageWidth;
				var hScale = document.body.clientHeight / then.stage.stageHeight;
				this.htmlCode.style.width = width * wScale + "px";
				this.htmlCode.style.height = height * hScale + "px";
				this.htmlCode.style.left = xPos * wScale + "px";
				this.htmlCode.style.top = yPos * hScale + "px";
				//横屏
			} else {
				var wScale = document.body.clientWidth / then.stage.stageHeight;
				var hScale = document.body.clientHeight / then.stage.stageWidth;
				this.htmlCode.style.width = height * wScale + "px";
				this.htmlCode.style.height = width * hScale + "px";
				this.htmlCode.style.top = (then.stage.stageWidth - xPos - width) * hScale + "px";
				this.htmlCode.style.left = yPos * wScale + "px";
			}
		}

		/**销毁*/
		public destroy() {
			if (this.htmlCode) {
				this.htmlCode.parentNode.removeChild(this.htmlCode);
				this.htmlCode = null;
			}
		}
	}

	export class SoundDisplay extends egret.Bitmap {
		private onTexture = RES.getRes("sound_on_png");
		private offTexture = RES.getRes("sound_off_png");
		private sound: egret.Sound;
		private sound_end: egret.SoundChannel
		constructor() {
			super();
			this.touchEnabled = false;
			if (document.querySelector('#bg_music')['paused']) {
				console.log('11')
				this.sound = new egret.Sound();
				this.sound.addEventListener(egret.Event.COMPLETE, function loadOver(event: egret.Event) {
					this.sound_end = this.sound.play(0, -1);
					this.touchEnabled = true;
				}, this);
				this.sound.load("resource/assets/Sound/bg.mp3");
			} else {
				this.touchEnabled = true;
			}
			this.texture = this.onTexture;
			this.touchEnabled = true;
			this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouch, this);
			this.addEventListener(egret.Event.ENTER_FRAME, this.onFrame, this);
			this.anchorOffsetX = this.width >> 1;
			this.anchorOffsetY = this.height >> 1;
			this.y = 60 + this.height / 2;
			this.x = 640 - this.width;

		}
		private onFrame(): void {
			if (this.isOpen) {
				this.rotation += 0.5;
			}
		}
		public isOpen: boolean = true;
		public onTouch(): void {
			this.isOpen = !this.isOpen;
			this.onOpenChange();
		}
		private position = 0;
		private onOpenChange(): void {
			if (this.isOpen) {
				this.texture = this.onTexture;
				window['muscPlay']();
			}
			else {
				this.texture = this.offTexture;
				window['muscStop']();
				this.rotation = 0;
				if (this.sound_end) {
					this.sound_end.stop()
					this.sound_end = null;
				}
			}
		}
	}
	/**
	 * 随机数
	 * @param min 最小
	 * @param max 最大
	 * @returns 
	 */
	export const randomNum = (min, max) => {
		// parseInt(Math.random() * (max - min + 1) + min, 10);
		return Math.floor(Math.random() * (max - min + 1) + min);
	}
	/**
	 * 调用相机/相册
	 */
	//用法
	// new pickPhoto().selectImage(this.selectedHandler, this)
	/**
	*  在回调函数中，接收3个参数:
	* thisRef : 就是this的引用，上面传入的那个
	* thisimgURL : 是选择的图片的缩略图的字符串数据(不是原图)，您可以用RES加载，来实现预览
	* file : 就是选择的那个照片文件引用，如果要上传原始数据，需要引用
	*/
	//  private selectedHandler(thisRef: any, imgURL: string, file: Blob): void {
	//     //用RES加载，即可显示到Egret中实现预览
	//     RES.getResByUrl(imgURL, thisRef.compFunc, thisRef, RES.ResourceItem.TYPE_IMAGE);
	// }
	// private compFunc(data,url){
	//     console.log(data,url)
	// }
	export class pickPhoto {
		public constructor() {

		}
		private mime = { 'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp' };
		private selectedHandler;
		private bytesHandler;
		private thisRef;
		private MAX_HEIGHT = 300;
		public selectImage(selectedFunc, thisValue) {
			this.selectedHandler = selectedFunc;
			this.thisRef = thisValue;
			var fileInput = <HTMLInputElement>document.getElementById("fileInput");
			if (fileInput == null) {
				fileInput = document.createElement("input");
				fileInput.id = "fileInput";
				fileInput.type = "file";
				fileInput.accept = "image/*";
				fileInput.style.height = "0px";
				fileInput.style.display = "block";
				fileInput.style.overflow = "hidden";
				document.body.insertBefore(fileInput, document.body.firstChild);
				fileInput.addEventListener('change', this.tmpSelectFile.bind(this), false);
			}
			setTimeout(function () { fileInput.click() }, 100);
		}
		public tmpSelectFile(evt) {
			//console.log("image selected...");
			var file = evt.target.files[0];
			var type = file.type;

			if (!type) {
				type = this.mime[file.name.match(/\.([^\.]+)$/i)[1]];
			}
			var ret = this.myCreateObjectURL(file);
			this.tmpCreateImage && this.tmpCreateImage(ret, file);
			var fileInput = <HTMLInputElement>document.getElementById("fileInput");
			fileInput.value = "";
		}
		public tmpCreateImage(uri, file?) {
			var image = new Image();
			image.onload = () => {

				var canvas = document.createElement("canvas");
				if (!this.isWeixin() && image.height > this.MAX_HEIGHT) {
					//宽度等比例缩放
					// image.width *= this.MAX_HEIGHT / image.height;
					// image.height = this.MAX_HEIGHT;
					var ctx = canvas.getContext("2d");
					ctx.clearRect(0, 0, canvas.width, canvas.height);
					canvas.width = image.width;
					canvas.height = image.height;
					ctx.drawImage(image, 0, 0, image.width, image.height);
					var smallURL = canvas.toDataURL("image/png");
				} else {
					smallURL = uri;
				}
				image.width = image.height = 1;
				this.selectedHandler & this.selectedHandler(smallURL, file);
			}
			image.src = uri;
			image.style.visibility = "hidden";
			document.body.appendChild(image);
		}
		public myCreateObjectURL(blob) {
			if (window.URL != undefined)
				return window['URL']['createObjectURL'](blob);
			else
				return window['webkitURL']['createObjectURL'](blob);
		}
		public myResolveObjectURL(blob) {
			if (window.URL != undefined)
				window['URL']['revokeObjectURL'](blob);
			else
				window['webkitURL']['revokeObjectURL'](blob);
		}

		public getImageData(file, bytesFunc, thisValue) {
			this.bytesHandler = bytesFunc;
			this.thisRef = thisValue;
			try { var reader = new FileReader(); }
			catch (err) { console.log("no support FileReader") }
			var _this = this
			function tmpLoad() {
				_this.bytesHandler && _this.bytesHandler(_this.thisRef, this.result);
			}
			reader.onload = tmpLoad;
			reader.readAsArrayBuffer(file);
		}
		public isWeixin() {
			if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
				return true;
			} else {
				return false;
			}
		}
		/**
		 * Created by shaoruiguo on 15/10/16.
		 */
		public selectImageWX(selectedFunc, thisValue) {
			this.selectedHandler = selectedFunc;
			this.thisRef = thisValue;
			window['wx'].chooseImage({
				count: 1, // 默认9
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: (res) => {
					var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
					//alert(localIds[0]);
					this.tmpCreateImage(localIds[0]);
				}
			});
		}

	}
	/**验证手机号 */
	export const checkPhone = (value) => {
		var reg = /^1[3-9]\d{9}$/; //验证规则 
		if (reg.test(value)) {
			return true;
		} else {
			return false
		}
	}
	/**
   * @param img 目标图片
   * @param color 光晕的颜色，十六进制，不包含透明度
   * @param alpha 光晕的颜色透明度，是对 color 参数的透明度设定。有效值为 0.0 到 1.0。例如，0.8 设置透明度值为 80%。
   * @param blurX 水平模糊量。有效值为 0 到 255.0（浮点）
   * @param blurY 垂直模糊量。有效值为 0 到 255.0（浮点）
   * @param strength 压印的强度，值越大，压印的颜色越深，而且发光与背景之间的对比度也越强。有效值为 0 到 255。暂未实现
   * @param quality 应用滤镜的次数，建议用 BitmapFilterQuality 类的常量来体现
   * @param inner 指定发光是否为内侧发光，暂未实现
   * @param knockout 指定对象是否具有挖空效果，暂未实现
   */
	export const filterFun = (img: any, color = 0x33CCFF, alpha = 0.8, blurX = 35, blurY = 35, strength = 2, quality = egret.BitmapFilterQuality.HIGH, inner = false, knockout = false) => {
		var glowFilter: egret.GlowFilter = new egret.GlowFilter(color, alpha, blurX, blurY,
			strength, quality, inner, knockout);
		img.filters = [glowFilter]
	}
	/**
	 * 清除滤镜
	 * @param image image对象
	 */
	export const clearFlilter = (image: egret.DisplayObject) => {
		image.filters = null;
	}

	/**图片等比例缩放 
	 * maxWidth
	 * maxHeight
	*/
	export const onCOMPLETE = (e: eui.Image) => {
		var tempWidth;
		var tempHeight;
		if (e.texture.textureWidth > 0 && e.texture.textureHeight > 0) {
			//原图片宽高比例 大于 指定的宽高比例，这就说明了原图片的宽度必然 > 高度
			if (e.texture.textureWidth / e.texture.textureHeight >= e.maxWidth / e.maxHeight) {
				if (e.texture.textureWidth > e.maxWidth) {
					tempWidth = e.maxWidth;
					// 按原图片的比例进行缩放
					tempHeight = (e.texture.textureHeight * e.maxWidth) / e.texture.textureWidth;
				} else {
					// 按原图片的大小进行缩放
					tempWidth = e.texture.textureWidth;
					tempHeight = e.texture.textureHeight;
				}
			} else {// 原图片的高度必然 > 宽度
				if (e.texture.textureHeight > e.maxHeight) {
					tempHeight = e.maxHeight;
					// 按原图片的比例进行缩放
					tempWidth = (e.texture.textureWidth * e.maxHeight) / e.texture.textureHeight;
				} else {
					// 按原图片的大小进行缩放
					tempWidth = e.texture.textureWidth;
					tempHeight = e.texture.textureHeight;
				}
			}
			// 设置页面图片的宽和高
			e.height = tempHeight;
			e.width = tempWidth;
		}
	}
	export const dataURLtoBlob = (dataurl) => {
		var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new Blob([u8arr], { type: mime });
	}
	/** base64 转 file */
	export const base64ConvertFile = (urlData) => {
		var arr = urlData.split(',')
		var type = arr[0].match(/:(.*?);/)[1]
		var fileExt = type.split('/')[1]
		var bstr = atob(arr[1])
		var n = bstr.length
		var u8arr = new Uint8Array(n)
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new File([u8arr], 'filename.' + fileExt, {
			type: type
		});
	}
	/**
  * base64转位图
  * @param str 图片路径
  * @return egret.Texture
  */
	export const base64ToTexture = (base64: string): Promise<egret.Texture> => {
		return new Promise((resolve, reject) => {
			let img: HTMLImageElement = new Image();//document.createElement("img");
			img.onload = () => {
				let bitmapData: egret.BitmapData = new egret.BitmapData(img);
				let texture: egret.Texture = new egret.Texture();
				texture.bitmapData = bitmapData;
				resolve(texture);
			}
			img.src = base64;
		})
	}
	/**
  * base64转位图
  * @param str 图片路径
  * @return egret.Texture
  */
	export const base64ToTexture2 = (base64: string) => {
		return new Promise((resolve, reject) => {
			let str = base64.replace("data:image/png;base64,", "");
			let bitmapdata: egret.BitmapData = egret.BitmapData.create("base64", str, (bmpData) => {
				let texture: egret.Texture = new egret.Texture();
				texture.bitmapData = bmpData;
				let bmp: egret.Bitmap = new egret.Bitmap(texture);
				resolve(bmp);
			});
		})
	}
	/**碰撞工具类 */
	export class Collision {
		/**
		 * 矩形包围盒碰撞检测
		 * 参数obj1,obj2要求是显示对象，必须有坐标和宽高
		 */
		public testRectangleHit(obj1: egret.DisplayObject, obj2: egret.DisplayObject): boolean {
			var b1Rect: egret.Rectangle = obj1.getBounds();
			var b2Rect: egret.Rectangle = obj2.getBounds();
			let poi = obj2.parent.localToGlobal(obj2.x, obj2.y)
			b1Rect.x = obj1.x; b1Rect.y = obj1.y;
			b2Rect.x = poi.x; b2Rect.y = poi.y;
			return b1Rect.intersects(b2Rect);
		}



		private aRect: egret.Rectangle;
		private bRect: egret.Rectangle;
		/**面与面检测,
		 * 参数a和b均为对象，
		 * (包围盒相交检测 this.aRect.intersects(this.bRect);) */
		public faceToFaceHit(a, b) {
			if (a != null && b != null) {
				if ((a.x + a.width < b.x) && (a.y + a.height < b.y)) {
					return false;
				}

				if ((a.x + a.width > b.x + b.width) && (a.y + a.height > b.y + b.height)) {
					return false;
				}

				if (!this.aRect) {
					this.aRect = new egret.Rectangle(a.x, a.y, a.width, a.height);
				} else {
					this.aRect.x = a.x;
					this.aRect.y = a.y;
					this.aRect.width = a.width;
					this.aRect.height = a.height;
				}

				if (!this.bRect) {
					this.bRect = new egret.Rectangle(b.x, b.y, b.width, b.height);
				} else {
					this.bRect.x = b.x;
					this.bRect.y = b.y;
					this.bRect.width = b.width;
					this.bRect.height = b.height;
				}

				return this.aRect.intersects(this.bRect);
			} else {
				return false;
			}
		}


		/**点与面的检测，
		 * 参数you为对象，x和y为检测点的坐标，
		 * （ you.hitTestPoint(x: number, y:number ) ） */
		protected faceToPointHit(you, x: number, y: number) {
			var isHit: boolean = you.hitTestPoint(x, y);
			return isHit;

		}


		/**点与面的像素检测，
		 * 据说很耗性能
		 * 像素碰撞检测，是判断显示对象的图案（非透明区域）是否与一点相交。
		 * 参数you为对象，x和y为检测点的坐标，
		 * （ you.hitTestPoint(x: number, y:number, true:boolean ) ） */
		protected pxFaceToPointHit(you, x: number, y: number) {
			var isHit: boolean = you.hitTestPoint(x, y, true);
			return isHit;

		}


		/**
		 * 圆与圆的检测
		 * 根据圆形的半径，检查圆形是否碰撞
		 * @ballA 圆形A
		 * @ballB 圆形B
		 * @radius 半径
		 * @return 是否碰撞
			*/
		public checkCircle(circleA: egret.DisplayObject, circleB: egret.DisplayObject) {
			let poi = circleB.parent.localToGlobal(circleB.x, circleB.y)
			var pA: egret.Point = new egret.Point(circleA.x, circleA.y);
			var pB: egret.Point = new egret.Point(poi.x, poi.y);
			if (egret.Point.distance(pA, pB) <= (circleA.width / 2 + circleB.width / 2)) {
				// var shp:egret.Shape = new egret.Shape();
				// shp.x = pA.x;
				// shp.y = pA.y;
				// shp.graphics.lineStyle( 10, 0x00ff00 );
				// shp.graphics.beginFill( 0xff0000, 1);
				// shp.graphics.drawCircle( 0, 0, 10 );
				// shp.graphics.endFill();

				// var shp2:egret.Shape = new egret.Shape();
				// shp2.x = pB.x;
				// shp2.y = pB.y;
				// shp2.graphics.lineStyle( 10, 0x00ff00 );
				// shp2.graphics.beginFill( 0xff0ff0, 1);
				// shp2.graphics.drawCircle( 0, 0, 15 );
				// shp2.graphics.endFill();
				// return [shp,shp2]
				// console.log(egret.Point.distance(pA, pB),circleA.width / 2 + circleB.width / 2)
				return true;
			}
			return false;
		}

		/**
		 * 多点与面检测（未完成）
		 * objA为主角对象（应该有 存有的需要检测的点 成员属性hitPointList[]）
		 * objB为需要碰撞的对象
		 * pointList 填充结构防报错（）
		 */
		protected checkHero(objA: egret.DisplayObject, objB: egret.DisplayObject, pointList: any[]) {
			//碰撞检测
			let rect = new egret.Rectangle(objB.x - objB.anchorOffsetX, objB.y -
				objB.anchorOffsetY, objB.width, objB.height);
			// let hitPointList = objA.hitPointList;
			let hitPointList = pointList;
			let len = hitPointList.length;
			let p: egret.Point = new egret.Point();

			//遍历碰撞点和矩形碰撞
			for (let i = 0; i < len; i++) {
				p = objA.localToGlobal(hitPointList[i].x, hitPointList[i].y);
				if (rect.containsPoint(p)) {
					console.log("hit");
					break;
				}
			}
		}

	}
	/**贝塞尔曲线 */
	export class Bezier {
		/**
		 * @desc 获取点，这里可以设置点的个数
		 * @param {number} num 点个数
		 * @param {Array} p1 点坐标
		 * @param {Array} p2 点坐标
		 * @param {Array} p3 点坐标
		 * @param {Array} p4 点坐标
		 * 如果参数是 num, p1, p2 为一阶贝塞尔
		 * 如果参数是 num, p1, c1, p2 为二阶贝塞尔
		 * 如果参数是 num, p1, c1, c2, p2 为三阶贝塞尔
		 */
		getBezierPoints(num = 100, p1, p2, p3?, p4?) {
			let func = null;
			const points = [];
			if (!p3 && !p4) {
				func = this.oneBezier;
			} else if (p3 && !p4) {
				func = this.twoBezier;
			} else if (p3 && p4) {
				func = this.threeBezier;
			}
			for (let i = 0; i < num; i++) {
				points.push(func(i / num, p1, p2, p3, p4));
			}
			// if (p4) {
			// 	points.push([...p4]);
			// } else if (p3) {
			// 	points.push([...p3]);
			// }
			return points;
		}

		/**
		 * @desc 一阶贝塞尔
		 * @param {number} t 当前百分比
		 * @param {Array} p1 起点坐标
		 * @param {Array} p2 终点坐标
		 */
		oneBezier(t, p1, p2) {
			const [x1, y1] = p1;
			const [x2, y2] = p2;
			let x = x1 + (x2 - x1) * t;
			let y = y1 + (y2 - y1) * t;
			return [x, y];
		}

		/**
		 * @desc 二阶贝塞尔
		 * @param {number} t 当前百分比
		 * @param {Array} p1 起点坐标
		 * @param {Array} cp 控制点
		 * @param {Array} p2 终点坐标
		 */
		twoBezier(t, p1, cp, p2) {
			const [x1, y1] = p1;
			const [cx, cy] = cp;
			const [x2, y2] = p2;
			let x = (1 - t) * (1 - t) * x1 + 2 * t * (1 - t) * cx + t * t * x2;
			let y = (1 - t) * (1 - t) * y1 + 2 * t * (1 - t) * cy + t * t * y2;
			return [x, y];
		}

		/**
		 * @desc 三阶贝塞尔
		 * @param {number} t 当前百分比
		 * @param {Array} p1 起点坐标
		 * @param {Array} cp1 控制点1
		 * @param {Array} p2 终点坐标
		 * @param {Array} cp2 控制点2
		 */
		threeBezier(t, p1, cp1, cp2, p2) {
			const [x1, y1] = p1;
			const [x2, y2] = p2;
			const [cx1, cy1] = cp1;
			const [cx2, cy2] = cp2;
			let x =
				x1 * (1 - t) * (1 - t) * (1 - t) +
				3 * cx1 * t * (1 - t) * (1 - t) +
				3 * cx2 * t * t * (1 - t) +
				x2 * t * t * t;
			let y =
				y1 * (1 - t) * (1 - t) * (1 - t) +
				3 * cy1 * t * (1 - t) * (1 - t) +
				3 * cy2 * t * t * (1 - t) +
				y2 * t * t * t;
			return [x, y];
		}
	}
	/**
	 * 
	 * @param base64 图片base64
	 * @param path 图片路径 '2022/202201/xxx/'
	 * @param name 图片名字 "qweasd"
	 * @param call 回调 返回URL   call(URL)
	 */
	export var up_img_oss = function (base64, path, name, call) {
		let file = Utils.dataURLtoBlob(base64)
		Utils.ajax({
			url: 'https://api.malukeji.com/lbdq/aliyunWebUploadSts/getSign.action'
		}).then(res => {
			const d = new Date();
			const str = d.valueOf() + '' + (Math.random() * 10000).toFixed(0);
			var formData = new FormData();
			// //注意formData里append添加的键的大小写
			formData.append('name', name + str + '.png');
			formData.append('key', res.data.dir + path + name + str + '.png'); //存储在oss的文件路径
			formData.append('policy', res.data.policy); //policy
			formData.append('OSSAccessKeyId', res.data.accessid); //accessKeyId
			formData.append('success_action_status', '200'); //成功后返回的操作码    
			formData.append('signature', res.data.signature); //签名
			//如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
			formData.append("file", file);
			const request = new egret.HttpRequest();
			request.responseType = egret.HttpResponseType.TEXT;
			request.open(res.data.host, egret.HttpMethod.POST);
			request.send(formData);
			request.addEventListener(egret.Event.COMPLETE, () => {
				console.log(res.data.host + '/' + res.data.dir + path + name + str + '.png');
				call(res.data.host + '/' + res.data.dir + path + name + str + '.png')
			}, this);
		})

	}
	/**
	 * 用法
	 * new pickVideo().selectVideo(this.selectedHandler, this)
	 */
	export class pickVideo {
		public constructor() {
		}
		private selectedHandler;
		private bytesHandler;
		private thisRef;
		private MAX_HEIGHT = 300;
		public selectVideo(selectedFunc, thisValue) {
			this.selectedHandler = selectedFunc;
			this.thisRef = thisValue;
			var fileInput = <HTMLInputElement>document.getElementById("fileInput");
			if (fileInput == null) {
				fileInput = document.createElement("input");
				fileInput.id = "fileInput";
				fileInput.type = "file";
				fileInput.accept = "video/*";
				fileInput.style.height = "0px";
				fileInput.style.display = "block";
				fileInput.style.overflow = "hidden";
				fileInput.style.position = 'fixed'
				document.body.insertBefore(fileInput, document.body.firstChild);
				fileInput.addEventListener('change', this.tmpSelectFile.bind(this), false);
			}
			setTimeout(function () { fileInput.click() }, 100);
		}
		public tmpSelectFile(evt) {
			var file = evt.target.files[0];
			var type = file.type;
			this.selectedHandler(file)
		}

	}
	/**
	 * 
	 * @param video file
	 * @param path 视频路径 '2022/202201/xxx/'
	 * @param name 视频名字 "qweasd"
	 * @param call 回调 返回URL   call(URL)
	 */
	export var up_video_oss = function (file, path, name, call) {
		Utils.ajax({
			url: 'https://api.malukeji.com/app-api/kuaike/aliyunWebUploadSts/getSign'
		}).then(res => {
			console.log(res);
			const d = new Date();
			const str = d.valueOf() + '' + (Math.random() * 10000).toFixed(0);
			var formData = new FormData();
			var fileExtension = file.name.split('.').pop();
			fileExtension = '.' + fileExtension
			// //注意formData里append添加的键的大小写
			formData.append('name', name + str + fileExtension);
			formData.append('key', res.data.dir + path + name + str + fileExtension); //存储在oss的文件路径
			formData.append('policy', res.data.policy); //policy
			formData.append('OSSAccessKeyId', res.data.accessid); //accessKeyId
			formData.append('success_action_status', '200'); //成功后返回的操作码    
			formData.append('signature', res.data.signature); //签名
			//如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
			formData.append("file", file);
			const request = new egret.HttpRequest();
			request.responseType = egret.HttpResponseType.TEXT;
			request.open(res.data.host, egret.HttpMethod.POST);
			request.send(formData);
			request.addEventListener(egret.Event.COMPLETE, () => {
				console.log(res.data.host + '/' + res.data.dir + path + name + str + fileExtension);
				call('https://creat.elloworld.cn/' + res.data.dir + path + name + str + fileExtension)
			}, this);
		})
	}
	/**数组乱序 */
	export const shuffle = (arr) => {
		var length = arr.length,
			randomIndex,
			temp;
		while (length) {
			randomIndex = Math.floor(Math.random() * (length--));
			temp = arr[randomIndex];
			arr[randomIndex] = arr[length];
			arr[length] = temp
		}
		return arr;
	}
	//生成不重复12位序列号
	export const serial_num_12 = () => {
		var d = new Date();
		var year = d.getFullYear();
		var month = d.getMonth() + 1;
		var date = d.getDate();
		var day = d.getDay();
		year = Number((year + "").substring(2));
		if (month <= 9) {
			month = Number("0" + month);
		} else if (date <= 9) {
			date = Number("0" + date);
		}
		//获取当日凌晨0:00:00（零时整）
		let startTime = parseInt(String(new Date(new Date().toLocaleDateString()).getTime()));
		//获取当日23:59:59
		let endTime = startTime + (24 * 60 * 60 * 1000 - 1);
		//获取当前时间戳
		let currentTime = parseInt(String(new Date().getTime()));
		let remainTime = parseInt(String((parseInt(String(endTime)) - parseInt(String(currentTime))) / 100));

		let time;
		if (parseInt(String(currentTime)) > parseInt(String(startTime))) {
			if (remainTime < 10) {
				time = "00000" + remainTime.toString();
			}
			if (remainTime < 100 && remainTime >= 10) {
				time = "0000" + remainTime.toString();
			}
			if (remainTime < 1000 && remainTime >= 100) {
				time = "000" + remainTime.toString();
			}
			if (remainTime < 10000 && remainTime >= 1000) {
				time = "00" + remainTime.toString();
			}
			if (remainTime < 100000 && remainTime >= 10000) {
				time = "0" + remainTime.toString();
			}
			if (remainTime >= 100000) {
				time = remainTime.toString();

			}
			let str = Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
			var id = year + month + date + time + str;
			return id;
		}

	}
	/**
	 * MD5加密
	 *  let data = {
	*      	 "timestamp": new Date().getTime(),
	 *       "noncestr": Utils.serial_num_12(),
	 *       "openid": 'openid',
	 *       "sign": ''
	 *   }
	 *   let sign = Utils.getSign(data)
	 *  let hash = CryptoJS.MD5(sign).toString().toUpperCase()
	 *   data.sign = hash
	 */
	export const getSign = (data) => {
		var keys = [];
		for (let k in data) {
			if (k == 'sign') {
				continue;
			}
			keys.push(k);
		}
		//排序
		keys.sort();
		//取value
		var kv = [];
		for (let k of keys) {
			if (data[k] != "") {
				kv.push(k + '=' + data[k])
			}
		}
		kv.push('key=yslgame20230209')
		return kv.join('&')
	}
}